#include "mainwindow.h"
#include "ui_mainwindow.h"
#define REG_RUN "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    this->hide();
    ui->setupUi(this);
    loadConfig();
    setAutoStart();
    tray_icon_ = new QSystemTrayIcon(this);
    connect(tray_icon_, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
            this, SLOT(SlotIconIsActived(QSystemTrayIcon::ActivationReason)));
    setSystemTray(":/res/info.png");
    isweboktimer.start(1200);
    connect(&isweboktimer,SIGNAL(timeout()),this,SLOT(CharckWeb()));
    ui->checkBox->setChecked(true);
    connect(ui->textBrowser, SIGNAL(cursorPositionChanged()), this, SLOT(autoScroll()));
}
void MainWindow::autoScroll() {
    QTextCursor cursor =  ui->textBrowser->textCursor();
    cursor.movePosition(QTextCursor::End);
    ui->textBrowser->setTextCursor(cursor);
}

void MainWindow::setAutoStart()
{
     bool is_auto_start=ui->startup->isChecked();
    QString application_name = QApplication::applicationName();
    QSettings *settings = new QSettings(REG_RUN, QSettings::NativeFormat);
    if(is_auto_start)
    {
        QString application_path = QApplication::applicationFilePath();
        settings->setValue(application_name, application_path.replace("/", "\\"));
    }
    else
    {
        settings->remove(application_name);
    }
    delete settings;
}
bool MainWindow::isWebOk()
{
    //能接通百度IP说明可以通外网
    return ipLive("180.101.49.11", 80);
}
bool MainWindow::ipLive(QString ip, int port, int timeout) {
    QTcpSocket tcpClient;
    tcpClient.abort();
    tcpClient.connectToHost(ip, port);
    //100毫秒没有连接上则判断不在线
    return tcpClient.waitForConnected(timeout);
}
void MainWindow::CharckWeb()
{

    if(isWebOk())
    {
        this->showNormal();
        ui->textBrowser->insertPlainText("连接成功！\n");
        isweboktimer.stop();
        ui->textBrowser->insertPlainText("爬取中.........\n");
        SRCdata = getHtml(QString("https://cn.bing.com") );
       QTimer::singleShot(3000,this,SLOT(finishedURL()));
    }
    else
    {
        ui->textBrowser->insertPlainText("网络连接中断，等待连接...\n");
        static int m_loop=0;
        m_loop++;
        if(m_loop==6)
        {
            this->hide();
            ui->textBrowser->insertPlainText("隐藏软件等待网络连接...\n");
        }
    }
}
bool MainWindow::saveConfig()
{


    bool isExist=false;
    for(keyIndex=0;keyIndex<PURLlist.count();keyIndex++)
    {
       if( PURLlist.at(keyIndex)==PURL)
       {
         isExist =true;
         break;
       }
    }
   if(!isExist)
   {
       ui->textBrowser->insertPlainText("此URL不存在本地，开始下载...\n");

       PURLlist.append(PURL);
       keylist.append(Picturestr);
    QSettings configIni ("Conf", QSettings::IniFormat);
    configIni.setValue("value/PURLlist",PURLlist);
    configIni.setValue("key/keylist",keylist);
    return false;
   }
   else
   {
       ui->textBrowser->insertPlainText("此URL已存在，检测图片是否存在\n");

       Picturestr=keylist.at(keyIndex);
       QString fileName = QDir::currentPath()+"/photo/" + Picturestr + ".jpg";//指定文件夹路径
       QFile  temp(fileName);
       qDebug()<<fileName<<"------------";
       if(temp.exists())
       {
       ui->textBrowser->insertPlainText("跳过下载步骤，直接设置壁纸...\n");
       setWallPaper(Picturestr);
       }
       else
       {
           ui->textBrowser->insertPlainText("此图片不存在，重新下载\n");
           PURLlist.removeAt(keyIndex);
           keylist.removeAt(keyIndex);

           QSettings configIni ("Conf", QSettings::IniFormat);
           configIni.setValue("value/PURLlist",PURLlist);
           configIni.setValue("key/keylist",keylist);
           isweboktimer.start();
       }
   }
}
bool MainWindow::DirMake(const QString &path) {
    QDir dir(path);
    if (dir.exists()) {
        return true;
    } else {
        return dir.mkpath(path);
    }
}
void MainWindow::loadConfig()
{
    QSettings configIni ("Conf", QSettings::IniFormat);
     PURLlist =configIni.value("value/PURLlist").toStringList();
     keylist =configIni.value("key/keylist").toStringList();     
     ui->startup->setChecked(configIni.value("func/startup").toBool());
         DirMake(QDir::currentPath()+"/photo");

}
void MainWindow::SlotIconIsActived(QSystemTrayIcon::ActivationReason reason) {
    switch (reason) {
        case QSystemTrayIcon::Trigger:
        case QSystemTrayIcon::DoubleClick: {
                this->showNormal();
                break;
            }
        default:
            break;
    }
}
void MainWindow::setSystemTray(QString strIcon)
{
    tray_icon_->setVisible(true);
    tray_icon_->setIcon(QIcon(strIcon));

}
void MainWindow::setWallPaper(QString sc)
{
    QSettings set("HKEY_CURRENT_USER\\Control Panel\\Desktop", QSettings::NativeFormat);
        QString path =QDir::currentPath()+"/photo/"+sc+".jpg";
//    QString path =QDir::currentPath().replace(':',":/")+"/"+sc+".jpg";
    qDebug() <<"path"<<path ;
//    QString path ="C://Users/Administrator/Documents/untitled/20200613233808.jpg";
        qDebug() <<"load..............." ;
        ui->textBrowser->insertPlainText(QString("设置壁纸中.....\n").arg(PURL));

    //把注册表的桌面图片路径改为指定路径.
    set.setValue("Wallpaper", path);
//    //修改背景风格.
//    set.setValue("WallpaperStyle", 2);
//    //修改是否平铺.
//    set.setValue("TileWallpaper",0);

    QByteArray byte = path.toLocal8Bit();
    //调用windows api.
    if(SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, byte.data(), SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE))
    {
        QSettings configIni ("Conf", QSettings::IniFormat);
        configIni.setValue("func/startup",ui->startup->isChecked());
        qDebug() <<"设置壁纸成功！" ;
        ui->textBrowser->insertPlainText("设置壁纸成功！\n");

        if(ui->checkBox->isChecked())
        {
        QTimer::singleShot(500,this,SLOT(close()));
        ui->textBrowser->insertPlainText("正在关闭......\n");
        qDebug() <<"closing..............." ;
        }

    }
    else
    {
        qDebug() <<"设置壁纸失败" ;
    }


}
bool MainWindow::downIURL_to_picture(const QString &url, const QString &fileName)
{
    //构造请求
    QNetworkAccessManager manager;
    QNetworkRequest request;
    request.setUrl(url);
    // 发送请求
    QNetworkReply *reply = manager.get(request);
    //开启一个局部的事件循环，等待响应结束，退出
    QEventLoop loop;
    QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
    loop.exec();
    //判断是否出错
    ui->textBrowser->insertPlainText(QString("图片下载中.....\n").arg(PURL));
    if (reply->error() != QNetworkReply::NoError)
    {
        return false;
    }
    //SAVE FILE
    QFile f(fileName);
    if(!f.open(QIODevice::WriteOnly))
        return false;
    f.write(reply->readAll());
    f.close();
    delete reply;
    return true;
}

QString MainWindow::getHtml(const QString &url)
{
    QNetworkAccessManager *manager = new QNetworkAccessManager();
    QNetworkReply *reply = manager->get(QNetworkRequest(QUrl(url)));
    QByteArray responseData;
    QEventLoop eventLoop;
    QObject::connect(manager, SIGNAL(finished(QNetworkReply *)), &eventLoop, SLOT(quit()));

    eventLoop.exec();
    qDebug() <<"爬取中.........";

    responseData = reply->readAll();

    return QString(responseData);
}

void MainWindow::finishedURL()
{
//    std::cout<<SRCdata.toStdString()<<endl;
    if(SRCdata.length()==0)
    {
        qDebug() <<"爬取源码失败";
        ui->textBrowser->insertPlainText("爬取源码失败\n");
        return;
    }
    else
    {
        qDebug() <<"爬取源码成功" <<SRCdata.length();
       ui->textBrowser->insertPlainText("爬取源码成功!\n");
    }


    QString t1,t2,t3;
    QString keyname;
    t1=SRCdata.split("background-image:url(/th?id=").at(1);
    PURL ="https://cn.bing.com/th?id="+t1.split(".jpg").at(0)+".jpg";
    qDebug() <<"PURLLLLLl" <<PURL;
    t2=SRCdata.split("class=\"sc_light\" title=\"").at(1);
    Picturestr =t2.split("\"").at(0);
    qDebug() <<"keyname" <<Picturestr;
    ui->textBrowser->insertPlainText("<--"+Picturestr+"\n");

//    Picturestr.replace('/',"");
//    Picturestr.replace('\\',"");
//    Picturestr.replace(':',"");
//    Picturestr.replace('?',"");
//    Picturestr.replace('“',"");
//    Picturestr.replace('<',"");
//    Picturestr.replace('>',"");
//    Picturestr.replace('｜',"");
    int nCount = Picturestr.count();
    for(int i = 0 ; i < nCount ; i++)
    {
        QChar cha = Picturestr.at(i);
        ushort uni = cha.unicode();
        if(!(uni >= 0x4E00 && uni <= 0x9FA5))
        {
                Picturestr.replace(i,1," ");
        }
    }
    Picturestr.replace(" ","");
    qDebug() <<"Picturestr" <<Picturestr;
    ui->textBrowser->insertPlainText("-->"+Picturestr+"\n");

    ui->textBrowser->insertPlainText(QString("URL  %1\n").arg(PURL));
    savePicture(PURL);
}

void MainWindow::errolURL()
{

}


MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::savePicture(QString url_name )
{
    QDateTime datetime;
//    Picturestr=datetime.currentDateTime().toString("yyyyMMddHHmmss");
    if(saveConfig()) return;

    QString fileName = QDir::currentPath()+"/photo/" + Picturestr + ".jpg";//指定文件夹路径
    qDebug() << "file:" << fileName << endl;
    qDebug() << "name:" << url_name << endl;
    downIURL_to_picture(url_name,fileName);
    transp(fileName);
}

void MainWindow::transp(QString fileName)
{
    ui->textBrowser->insertPlainText(QString("图片下载完成正在转换中.....\n").arg(PURL));

            QImage image(fileName);
            image.save(fileName, "JPG", 100);

        qDebug() << "finsh"<<Picturestr;
        setWallPaper(Picturestr);

}

